/*
 *
 * @ProjectName:    my_umi_app
 * @Package:
 * @ClassName:      add_tag
 * @Description:    JSX文件
 * @Author:         SuPeiSen
 * @CreateDate:     2021/1/21 11:45 上午
 * @UpdateDate:     2021/1/21 11:45 上午
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
import { ColorWidget } from '@/widget/color_widget/color_widget';
import React, { useRef, useState } from 'react';
import { Button, Form, Input, Row, Switch, message } from 'antd';
import { RGBColor } from 'react-color';
import { addTagApi, updateTagApi } from '@/service/tap_api';
import {
  useParams,
  useRouteMatch,
  useLocation,
  IRouteComponentProps,
} from 'umi';
import { history } from 'umi';
import { QiNiuUploadWidget } from '@/widget/qiniu_upload_widget/qiniu_upload_widget';
import { AppConfig } from '@/config/app_config';

// 定义query类型
interface TagParam {
  tag_name?: string;
  tag_color?: string;
  id?: string;
  status?: string;
  icon_url?: string;
}

export default (props: IRouteComponentProps<{}, TagParam>) => {
  const queryParam = props.location.query;

  // 上传图标
  let articleUrl = useRef<{ url: string }>({ url: '' });

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  const [loading, setLoading] = useState<boolean>(false);
  const tagNameRef = useRef<Input>(null);

  //提交表单
  const submitInput = async () => {
    const tagColor = `${tagRgbColor.r}-${tagRgbColor.g}-${tagRgbColor.b}-${tagRgbColor.a}`;
    if (queryParam.id === undefined) {
      const param = {
        tag_name: tagNameRef.current!.state.value,
        tag_color: tagColor,
        status: selectStatus ? 1 : -1,
        icon_url: articleUrl.current.url,
      };
      setLoading(true);
      const success = await addTagApi(param, () => {
        setLoading(false);
      });
      if (success) {
        message.success('添加成功');
        history.push('/admin/tag/tag_list');
      } else {
        message.error('添加失败');
      }
    } else {
      const param = {
        tag_name: tagNameRef.current!.state.value,
        tag_color: tagColor,
        status: selectStatus ? 1 : -1,
        id: queryParam.id,
        icon_url: articleUrl.current.url,
      };
      setLoading(true);
      const success = await updateTagApi(param, () => {
        setLoading(false);
      });
      if (success) {
        message.success('更新成功');
        history.push('/admin/tag/tag_list');
      } else {
        message.error('更新失败');
      }
    }
  };

  // 维护Switch状态
  let selectStatus = true;

  const switchOnChange = (value: boolean) => {
    selectStatus = value;
  };

  // tag颜色，默认是黑色
  let tagRgbColor: RGBColor = { r: 0, g: 0, b: 0, a: 1 };
  if (queryParam.tag_color != undefined) {
    const rgbaList = queryParam.tag_color.split('-');
    if (rgbaList.length === 4) {
      tagRgbColor = {
        r: Number(rgbaList[0]),
        g: Number(rgbaList[1]),
        b: Number(rgbaList[2]),
        a: Number(rgbaList[3]),
      };
    }
  }
  const colorSelectCallback = (color: RGBColor) => {
    // tagRgbColor = `${color.r}-${color.g}-${color.b}-${color.a}`;
    tagRgbColor = color;
  };

  return (
    <div className="main_div">
      <Row justify="start">
        <Form {...layout} onFinish={submitInput}>
          <Form.Item
            label="Tag名称"
            name="tag_name"
            rules={[
              {
                required: true,
                message: 'Tag名称',
              },
            ]}
            initialValue={queryParam?.tag_name ?? ''}
          >
            <Input className="inputLen" ref={tagNameRef} />
          </Form.Item>

          <Form.Item
            label="文章图片"
            name="article_image"
            style={{ width: '300px' }}
            valuePropName="fileList"
          >
            {/*Tag对应的图片*/}
            <QiNiuUploadWidget
              onSelect={(url) => {
                articleUrl.current.url = url;
              }}
              initValue={
                queryParam.icon_url === undefined
                  ? []
                  : [
                      {
                        uid: `${queryParam!.id}`,
                        name: queryParam?.tag_name ?? '',
                        status: 'done',
                        type: '',
                        url: AppConfig.ImageDoMain + queryParam!.icon_url,
                        size: 0,
                      },
                    ]
              }
            />
          </Form.Item>

          <Form.Item label="Tag颜色" valuePropName="category_status">
            <ColorWidget
              selectColor={colorSelectCallback}
              initColor={tagRgbColor}
            />
          </Form.Item>

          <Form.Item label="状态" valuePropName="category_status">
            <Switch
              defaultChecked={queryParam?.status == '1' ? true : false ?? true}
              onChange={switchOnChange}
            />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              loading={loading}
            >
              保存
            </Button>
          </Form.Item>
        </Form>
      </Row>
    </div>
  );
};
